var express = require('express');
var router = express.Router();

const helper = require('../../util/helper');
const log = require('../../../core/logger').getLogger("system");
const roleService  = require("../../services/admin/roleService");
const userService  = require("../../services/admin/userService");

module.exports = router;

/* GET users listing. */
router.get('/', (req, res, next) => {
    res.render('admin/user_role', {
        user: req.session.user,
        menus: req.session.menus,
        menu_active: req.session.menu_active['/user_role'] || {},
        title: '用户角色管理'
    });
});

router.get('/load', async(req, res, next) => {
    var {name, user_name, start, length, draw} = req.query;
    name = name?name.trim():null;
    user_name = user_name?user_name.trim():null;
    if (!start || !length || !draw) {
        return res.status(401).json("invoke error!");
    }

    draw = parseInt(draw) || 0;
    start = parseInt(start) || 0;
    length = parseInt(length) || 0;

    userService.getUsers(name, user_name, start, length, async function (err, data) {
        if (!!err){
            return res.status(200).json({error:err.errCode, msg:err.message});
        }

        var result = { draw: draw, recordsTotal: data.count, recordsFiltered: data.count, data: [] };
        for (var i = 0; i < data.rows.length; i++) {
            var user = data.rows[i];
            var params = user.toParams();
            var role_ids = [], role_names = [];
            var roles = await userService.getUserRoles(user.id);
            roles.forEach(function (role) {
                role_ids.push(role.role_id);
                role_names.push(role.role_name);
            });
            params.role_id = role_ids.join(',');
            params.role_name = role_names.join(',');
            result.data.push(params);
        }

        return res.status(200).json(result);
    });
});

router.get('/get_role', async(req, res, next) => {
    roleService.getAllRoles(function (err, roles) {
        if (!!err){
            log.error("user_role get role: " + e.stack);
            return res.json({error:1, msg:"加载角色失败，请联系管理员"});
        }
        return res.json({error:0, data:roles});
    });
});

router.post('/set_role', async(req, res, next) => {
    var user = req.session.user;
    var user_id = req.body.e_id || 0;
    var roles = req.body.e_roles || [];
    userService.setUserRoles(user_id, roles, async function (err, result) {
        if (!!err){
            log.error("user_role set role: " + e.stack);
            return res.json({error:1, msg:"设置用户角色失败，请联系管理员"});
        }

        if (user_id == user.id) {
            await helper.setMenus(req, user.id);
        }

        await helper.saveOpLog(user.id, user.user_name, user.name, "绑定用户ID:"+user_id+";roles:"+roles);

        return res.json({error:0, msg:"ok"});
    });
});